<?php
/**
 * Created by PhpStorm.
 * User: User
 * Date: 2017/12/25
 * Time: 10:37
 */

namespace Kinfy\Cache\Drivers;

use Kinfy\Config;

class FileCache
{

    public function get($key)
    {
        $file = $this->getKeyFile($key);
        if (file_exists($file)) {
            $value = include($file);
            return unserialize($value);
        } else {
            return null;
        }
    }

    /**
     * @param $key 键
     * @param $value 值
     * @param int $expire 过期时间，单位秒，-1表示永不过期
     */
    public function set($key, $value, $expire = -1)
    {
        $file = $this->getKeyFile($key);
        $value = serialize($value);
        $expire = time() + $expire;

        if ($expire == -1) {
            $content = "<?php 
            return '{$value}';";
        } else {
            $content = "<?php
            if(time()>={$expire}){
                unlink(__FILE__);
                return null;
            }else{
                return '{$value}';
            }";
        }

        file_put_contents($file, $content);
    }

    public function exsit($key)
    {
        $file = $this->getKeyFile($key);
        return file_exists($file);
    }

    public function del($key)
    {
        $file = $this->getKeyFile($key);
        if (file_exists($file)) {
            unlink($file);
        }
    }

    public function clear()
    {
    }

    protected function getKeyFile($key)
    {
        return Config::get('cache.cache_dir') . '/' . md5($key) . '.php';
    }

}